#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys,json
sys.path.append("./cow")
from database import con 
from .scheme import Exchange,Scheme

from .data import(
    scheme_dates,
    scheme_codes,
    scheme_param,
    etfOHLC,
    storeOHLC,
    scheme_clear_backtrade,
    scheme_trade_nosellorder,
    scheme_trade_minprice
) 

class Koinu(Scheme):
    
    def __init__(self,id:int):
        Scheme.__init__(self)
        self.id = id
        
        # 获取股票列表
        self.param = scheme_param(strategyId=self.id)
        self.storecodes = list(scheme_codes(strategyId=self.id,type=1))
        self.etfcodes = list(scheme_codes(strategyId=self.id,type=1))
        dates = list(scheme_dates(self.id))
        self.dates = sorted(dates)
    

    def setup(self):
        scheme_clear_backtrade(self.id)
        return self.dates

    def willopen(self,index,item):
        print("开盘了！买定离手",str(item))
        if index==0:
            return []
        date = self.dates[index-1]
        # ETF 根据前一天数据获取满足条件的挂单
        etfbuy0 = self.befororder_buy(date = date,type=1)
        etfbuy = self.fitter_befororder_buy(date,type=1,result=etfbuy0)
        storebuy0 = self.befororder_buy(date = date,type=0)
        storebuy = self.fitter_befororder_buy(date,type=1,result=storebuy0)
        etfsell0 = self.befororder_sell(date = date,type=1)
        etfsell = self.fitterbefororder_sell(date = date,type=1,result=etfsell0)
        storesell0 = self.befororder_sell(date = date,type=0)
        storesell = self.fitterbefororder_sell(date = date,type=0,result=storesell0)
        return etfbuy+storebuy+etfsell+storesell
    # etf 获取买入单
    def befororder_buy(self,date,type):
        # 获取满足条件的etf
        fastma = ("ma%s" % self.param["fastma"])
        slowma = ("ma%s" % self.param["slowma"])
        codes = []
        if type == 0:
            codes = self.storecodes
        elif type == 1:
            codes = self.etfcodes
        
        codesstr = ",".join(map(lambda x: ("'%s'" %x),codes))
        if type == 0:
            sql = ("""
            SELECT code from damreystock
            where %s>%s and date='%s' and code in (%s)
            """ % (fastma,slowma,date,codesstr))
        elif type == 1:
            sql = ("""
            SELECT code from damreyetf
            where %s>%s and date='%s' and code in (%s)
            """ % (fastma,slowma,date,codesstr))
        cur = con.cursor()
        cur.execute(sql)
        result = cur.fetchall()
        return result
        
    def fitter_befororder_buy(self,date, type, result):
        etforders = []
        for item in result:
            code= item["code"]
            ohlc = None
            if type==0:
                ohlc = storeOHLC(code=code,date=date)
            elif type == 1:
                ohlc = etfOHLC(code=code,date=date)
            if ohlc == None:
                continue
            oprice = ohlc["close"]
            minprice = scheme_trade_minprice(self.id,code)
            if minprice!=None and oprice>minprice*0.9:
                continue
            dict = {}
            dict["code"]= code
            dict["price"] = oprice
            dict["count"] = 100
            dict["type"]= type
            dict["dir"]= 0 # 买卖方向 0买 1卖
            etforders.append(dict)
        return etforders

    # 获取卖出单
    def befororder_sell(self,date,type):
        # 获取本期推荐code
        fastma = ("ma%s" % self.param["fastma"])
        slowma = ("ma%s" % self.param["slowma"])
        codes = []
        
        if type == 0:
            codes = self.storecodes
        elif type == 1:
            codes = self.etfcodes
        codesstr = ",".join(map(lambda x: ("'%s'" %x),codes))

        sql = ""
        if type == 0:
            sql = ("""
            SELECT code from damreystock
            where %s>%s and date='%s' and code in (%s)
            """ % (fastma,slowma,date,codesstr))
        elif type == 1:
            sql = ("""
            SELECT code from damreyetf
            where %s>%s and date='%s' and code in (%s)
            """ % (fastma,slowma,date,codesstr))

        
        cur = con.cursor()
        cur.execute(sql)
        result = cur.fetchall()
        codes= list(map(lambda x: x["code"], result))
        # 获取持仓code  
        sells = scheme_trade_nosellorder(self.id,codes,type,date) 
        return sells
    
    # 获取卖出单
    def fitterbefororder_sell(self,date,type,result):
        orders = []
        for item in result:
            code = item["code"]
            price = item["price"]
            ohlc = {}
            if type == 0:
                ohlc = storeOHLC(code=code,date=date)
            elif type == 1:
                ohlc = etfOHLC(code=code,date=date)
            if ohlc == None:
                continue
            if ohlc["close"]/price>=1.05:
                dict = {}
                dict["price"]=ohlc["close"]
                dict["code"]= code
                dict["count"] = item["count"]
                dict["type"]= type
                dict["dir"]= 1 # 买卖方向 0买 1卖
                dict["sid"] = item["id"]
                orders.append(dict)
        return orders



if __name__ == '__main__':
    ex = Exchange(scheme=Koinu(id=1))
    ex.main() 